package com.zyb.ext.databasepool.property;

import lombok.Data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Data
public class DBBean {

    //连接池支持的最大连接数，这里取值为20，表示同时最多有20个数据库连接。一般把maxActive设置成可能的并发量就行了设 0 为没有限制。
    private int maxActiveConnNum = 100;
    //连接池中最多可空闲maxIdle个连接 ，这里取值为20，表示即使没有数据库连接时依然可以保持20空闲的连接，而不被清除，随时处于待命状态。设 0 为没有限制。
    private int maxIdleConnNum = 10;
    //连接池中最小空闲连接数，当连接数少于此值时，连接池会创建连接来补充到该值的数量
    private int minIdleConnNum = 2;
    //初始化连接数目
    private int initConnNum = 0;
    //连接池中连接用完时,新的请求等待时间,毫秒，这里取值-1，表示无限等待，直到超时为止，也可取值9000，表示9秒后超时。超过时间会出错误信息
    private int maxWaitTime = 1000;
    //驱动名称
    private String driverName = "com.mysql.jdbc.Driver";
    //数据库url
    private String url = "jdbc:mysql://localhost:3306/test";
    //登入账户
    private String userName = "root";
    //登录密码
    private String password = "1112";
    //连接池名称
    private String poolName = "thread001";

    public int update(Connection connection, String sql, List<Object> params) throws SQLException {
        PreparedStatement preparedStatement = getPreparedStatement(connection, sql, params);
        return preparedStatement.executeUpdate();
    }

    public int insert(Connection connection, String sql, List<Object> params) throws SQLException {
        PreparedStatement preparedStatement = getPreparedStatement(connection, sql, params);
        return preparedStatement.executeUpdate();
    }


    public void select(Connection connection, String sql, List<Object> params) throws SQLException {
        PreparedStatement preparedStatement = getPreparedStatement(connection, sql, params);
        ResultSet resultSet = preparedStatement.executeQuery();
        int columnCount = resultSet.getMetaData().getColumnCount();
        while (resultSet.next()) {
            for (int i = 0; i < columnCount; i++) {
                System.out.print(resultSet.getString(i + 1) + "\t");
            }
        }
    }

    public int delete(Connection connection, String sql, List<Object> params) throws SQLException {
        PreparedStatement preparedStatement = getPreparedStatement(connection, sql, params);
        return preparedStatement.executeUpdate();
    }

    private PreparedStatement getPreparedStatement(Connection connection, String sql, List<Object> params) throws SQLException {
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        if (params != null && !params.isEmpty()) {
            for (int i = 0; i < params.size(); i++) {
                preparedStatement.setObject(i + 1, params.get(i));
            }
        }
        return preparedStatement;
    }
}
